package ta.utils;

import java.util.List;

public class ModelGenerator
{
	static String rt = "\r\t";
	// 创建Model类
	public static void createModel(List<String> tablelist)
	{		
		for (String tablename : tablelist)
		{
			String className=toFirstUpperCase(tablename);
			List<String[]> colsList = TableMeta.getColumnDatas(tablename);
			StringBuilder sb = new StringBuilder();
			sb.append("package " + CodeConfig.BeanPackageName + ";\n");
			//sb.append("import java.text.*;\n");
			sb.append("public class " + className + "{" + rt);
			// 创建类，类名为表名首字母大写
			for (String[] col : colsList)
			{
				//根据数据库字段备注生成成员变量注释
				sb.append("//" + (col[2].length() > 0 ? col[2] : col[0]) + rt);
				//声明成员变量
				sb.append("private " + col[1] + " " + col[0] + ";" + rt);
				// 创建get方法
				sb.append("public " + col[1] + " get"
						+ toFirstUpperCase(col[0]) + "()" + rt);
				sb.append("{" + rt);
				sb.append("\treturn this." + col[0] + ";" + rt);
				sb.append("}" + rt);
				//创建set方法
				sb.append(
						"public void set" + toFirstUpperCase(col[0]) + "(" + col[1] + " "
								+ col[0] + ")" + rt);
				sb.append("{" + rt);
				sb.append("\tthis." + col[0] + "=" + col[0] + ";" + rt);
				sb.append("}" + rt + rt);
			}
			//重写toString方法
			sb.append("@Override" + rt);
			sb.append("public String toString()" + rt);
			sb.append("{" + rt);		
			sb.append("\treturn \"[\"+");
			int n = 0;
			
			for (String[] col : colsList)
			{
				if (n == colsList.size() - 1)
				{
					sb.append("\" " + col[0] + "=\"+" + col[0]);
					break;
				}
				sb.append("\" " + col[0] + "=\"+" + col[0] + "+");			
				n++;
			}
			sb.append("+\"]\";" + rt);
			sb.append("}" + rt + rt);
			sb.append("\n}" + rt);
			// 创建文件
			FileHelper.genModuleTpl(
					CodeConfig.getRoot(CodeConfig.modelPath + "\\"
							+ className+ ".java"),
					sb.toString());
			System.out.println(
					CodeConfig.BeanPackageName + ": " + tablename + " 创建成功!");

		}
	}

	/**
	 * 首字母大写
	 * @return
	 */
	public static String toFirstUpperCase(String s)
	{
		return s.substring(0, 1).toUpperCase()+ s.substring(1);
	}
	
	public static void main(String[] args)
	{
		List<String> list=TableMeta.getTables();		
		createModel(list);
	}
	
}
